<template>
    <div class="container">
        <div class="form-box">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="分销商：" prop="distributorId" :disabled="!form.id?false:true">
                    <el-select v-model="form.teahouseId" @change="handleBrandChange" placeholder="请选择分销商">
                        <el-option v-for="item in brandOptions" :key="item.value" :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品分类：" prop="productCategoryId">
                    <el-cascader v-model="selectProductCateValue" :options="productCateOptions">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="商品标题">
                    <el-input v-model="form.title" placeholder="请输入商品标题"></el-input>
                </el-form-item>
                <el-form-item label="副标题">
                    <el-input v-model="form.subTitle" placeholder="请输入副标题"></el-input>
                </el-form-item>
                <el-form-item label="标签">
                    <el-input v-model="form.label" placeholder="请输入产品标签，多标签之间用‘,’隔开，如 '多汁,美味' "></el-input>
                </el-form-item>
                <el-form-item label="视频地址">
                    <el-input v-model="form.videoUrl" placeholder="请输入视频地址"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
                <el-form-item label="展示图">
                    <el-upload
                            class="avatar-uploader"
                            :headers="myHeaders"
                            :action="uploadsrc"
                            accept="image/jpeg,image/gif,image/png"
                            list-type="picture-card"
                            :limit="1"
                            :before-upload="handleBeforeUpload"
                            :on-success="uploadLogoSuccess"
                            :on-error="uploadError"
                            :data="pdfData"
                            :file-list="logolist"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="form.listLogo">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="轮播图">
                    <el-upload
                            class="avatar-uploader"
                            :headers="myHeaders"
                            :action="uploadsrc"
                            accept="image/jpeg,image/gif,image/png"
                            list-type="picture-card"
                            :limit="6"
                            :before-upload="handleBeforeUpload"
                            :on-success="uploadSuccess"
                            :on-error="uploadError"
                            :on-remove="handleRemove"
                            :data="pdfData"
                            :file-list="imglist"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="form.detailBanner">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品介绍">
                    <quill-editor ref="myTextEditor" v-model="form.introduce" @change="introduceHtml"></quill-editor>
                </el-form-item>
                <el-form-item label-width="255px">
                    <el-button type="primary" @click="onSubmit(form)">点击修改商品</el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';

    const util = require('../../../utils/geturlkey');
    import { uploadsrc } from '../../../utils/dcf2d0812e764796a97bb2e8c1725fab.js';
    import { dynamicHeader } from '../../../utils/dcf2d0812e764796a97bb2e8c1725fab.js';

    export default {
        name: 'addVoucher',
        data() {
            return {
                parentId: 0,
                parentid: 0,
                parentids: [],
                categoryIds: [],
                imageUrl: '',
                imglist: [],
                ortool: true,
                distributorIds: [],
                productCateOptions: [],
                selectProductCateValue: [],
                productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
                logolist: [],
                pdfData: {
                    type: 1,
                    path: 1
                },
                submit: {
                    detailBanner: ''
                },
                fromId: '',
                myHeaders: {},
                form: {
                    detailBanner: ''
                },
                distributorId: '',
                oldNumber: 0,
                filterAttrs: [],
                brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
                brandOptions: []
            };
        },
        watch: {
            //商品分类 展示
            selectProductCateValue: function(newValue) {
                if (newValue != null && newValue.length === 2) {
                    this.form.categoryId = newValue[1];
                    console.log('newValue' + newValue);
                    console.log('这里是几' + this.form.categoryId);
                    this.form.categoryName = this.getCateNameById(this.form.categoryId);
                } else {
                    this.form.categoryId = null;
                    this.form.categoryName = null;
                }
            }
        },
        created() {
            this.uploadsrc = uploadsrc;
            let id = util.getUrlKey('id');
            console.log(id);
            // let distributorId = util.getUrlKey('distributorId');
            if (id == null || id == '') {
                layer.alert('未获取到参数ID', {
                    icon: 2,
                    skin: 'layer-ext-moon'
                }, function() {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                });
            }
            this.getDistributorList();
            goodsDetail(id).then(res => {
                if (res.returnCode == 200) {
                    console.log(res.data.parentCategoryId);
                    console.log(res.data.categoryId);
                    console.log(res.data.teahouseId);
                    console.log(this.selectProductCateValue);
                    this.selectProductCateValue = res.data.categoryId ? [res.data.categoryId, res.data.parentCategoryId] : [];
                    this.handleBrandChange = res.data.teahouseId;
                    this.form = res.data;
                    this.imglist = [];
                    this.logolist = [];
                    if (res.data.detailBanner) {
                        var imgs = res.data.detailBanner.indexOf(',') > -1 ? res.data.detailBanner.split(',') : [res.data.detailBanner];
                        console.log(imgs);
                        this.form.detailBanner = imgs;
                        for (var i = 0; i < imgs.length; i++) {
                            var img = {
                                url: imgs[i]
                            };
                            this.imglist.push(img);
                        }
                    }
                    if (res.data.listLogo) {
                        this.logolist = [{
                            url: res.data.listLogo
                        }];
                    }
                } else {
                    layer.alert(res.returnMsg, {
                        icon: 2,
                        skin: 'layer-ext-moon'
                    }, function() {
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    });
                }
                this.selectProductCateValue(this.form.categoryId);
            });
        },

        methods: {
            introduceHtml({ editor, html, text }) {
                this.form.introduce = html;
            },
            productFeaturesHtml({ editor, html, text }) {
                this.form.productFeatures = html;
            },
            afterSaleServiceHtml({ editor, html, text }) {
                this.form.afterSaleService = html;
            },
            getDistributorList() {
                teahouseList({ pageNum: 1, pageSize: 100, param: {} }).then(res => {
                    this.brandOptions = [];
                    let distributorList = res.data.list;
                    for (let i = 0; i < distributorList.length; i++) {
                        this.brandOptions.push({ label: distributorList[i].name, value: distributorList[i].id });
                    }
                });
                this.getProductCateList();
            },
            handleBrandChange(val) {
                let brandName = '';
                let id = null;
                for (let i = 0; i < this.brandOptions.length; i++) {
                    if (this.brandOptions[i].value === val) {
                        brandName = this.brandOptions[i].label;
                        id = this.brandOptions[i].value;
                        break;
                    }
                }
                this.form.brandName = brandName;
                this.fromId = id;
            },
            //处理编辑逻辑  商品分类  categoryId  parentCategoryId
            handleEditCreated() {
                if (this.form.categoryId != null) {
                    this.selectProductCateValue.push(this.form.parentId);
                    this.selectProductCateValue.push(this.form.parentId);
                }
                this.hasEditCreated = true;
            },
            getProductCateList() {
                listWithChildren().then(res => {
                    let list = res.data;
                    this.productCateOptions = [];
                    for (let i = 0; i < list.length; i++) {
                        let children = [];
                        if (list[i].children != null && list[i].children.length > 0) {
                            for (let j = 0; j < list[i].children.length; j++) {
                                children.push({ label: list[i].children[j].name, value: list[i].children[j].id });
                            }
                        }
                        this.productCateOptions.push({ label: list[i].name, value: list[i].id, children: children });
                        console.log(this.productCateOptions);
                    }
                });
            },
            getCateNameById(id) {
                let name = null;
                for (let i = 0; i < this.productCateOptions.length; i++) {
                    for (let j = 0; j < this.productCateOptions[i].children.length; j++) {
                        if (this.productCateOptions[i].children[j].value == id) {
                            name = this.productCateOptions[i].children[j].label;
                            return name;
                        }
                    }
                }
                return name;
            },
            onSubmit(row) {
                this.submit = row;
                var detailBanner = '';
                if (row.detailBanner != null) {
                    detailBanner = row.detailBanner.length > 1 ? row.detailBanner.join(',') : row.detailBanner[0];
                }
                this.submit.detailBanner = detailBanner;
                updateGoods(this.submit).then(res => {
                    if (res.returnCode == 200) {
                        layer.alert('修改商品成功', function() {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                        });
                        layer.open({
                            type: 2,
                            area: ['90%', '90%'],
                            title: '添加规格',
                            fixed: true, //不固定
                            maxmin: true,
                            content: ['/#/productSpecsUpdate?id=' + form.id, 'yes']
                        });
                    } else {
                        layer.alert(res.returnMsg, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        });
                    }
                    layer.close(index);
                });

            },
            onDetail(row) {
                layer.open({
                    type: 2,
                    area: ['60%', '85%'],
                    title: '修改规格',
                    fixed: true, //不固定
                    maxmin: true,
                    content: ['/#/productSpecsUpdate?id=' + row.id, 'yes']
                });
            },
            uploadError(data) {
                this.$message.success(`上传失败，请重新上传`);
            },
            handleRemove(data) {
                var detailBanner = this.form.detailBanner;
                var index = detailBanner.indexOf(data.data);
                this.form.detailBanner.splice(index, 1);
            },
            uploadLogoSuccess(data) {
                if (data.returnCode == 200) {
                    this.form.listLogo = data.data;
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            uploadSuccess(data) {
                if (data.returnCode == 200) {
                    if (this.form.detailBanner == null) {
                        this.form.detailBanner = [];
                    }
                    this.form.detailBanner.push(data.data);
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            getmyHeaders() {
                var dHeader = dynamicHeader();
                this.myHeaders.signature = dHeader.signature;
                this.myHeaders.nonce = dHeader.nonce;
                this.myHeaders.timestamp = dHeader.timestamp;
                this.myHeaders.appkey = dHeader.appkey;
                this.myHeaders.token = dHeader.token;
            },
            handleBeforeUpload(file) {
                this.handleimgtype(file);
                this.getmyHeaders();
            },
            handleimgtype(file) {
                if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
                    this.$notify.warning({
                        title: '警告',
                        message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
                    });
                    return false;
                }
                let size = file.size / 1024 / 1024 / 2;
                if (size > 2) {
                    this.$notify.warning({
                        title: '警告',
                        message: '图片大小必须小于2M'
                    });
                    return false;
                }
            },
            cancel() {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            }
        }
    };
</script>